﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;

namespace Sino.CapacityCloud.Services
{

    public class JsonSerializer
        : ISerializer
    {

        public object SerializeObject(Type type, object data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            return type == null ? JsonConvert.SerializeObject(data) : JsonConvert.SerializeObject(data, type, new JsonSerializerSettings());
        }

        public object SerializeObject<T>(T data)
        {
            return this.SerializeObject(typeof(T), data);
        }

        public object SerializeObject(object data)
        {
            return this.SerializeObject(data.GetType(), data);
        }

        public Stream SerializeObjectToStream(object data)
        {
            return this.SerializeObjectToStream(data.GetType(), data);
        }

        public Stream SerializeObjectToStream<T>(T data)
        {
            return this.SerializeObjectToStream(typeof(T), data);
        }

        public Stream SerializeObjectToStream(Type type, object data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            var s = type == null ? JsonConvert.SerializeObject(data) : JsonConvert.SerializeObject(data, type, new JsonSerializerSettings());
            return new MemoryStream(Encoding.UTF8.GetBytes(s));
        }

    }

}